package cn.nkjobsearch.html;

import java.io.IOException;
import java.io.InputStreamReader;
//import java.io.PrintWriter;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import cn.nkjobsearch.config.Config;
import cn.nkjobsearch.config.ConfigZhilian;
import cn.nkjobsearch.mysql.MysqlConn;
import cn.nkjobsearch.publicClass.File;

public class ComZhilianSearchList extends Thread {
	public ComZhilianSearchList() {
		mysql = new MysqlConn();
	}
	
	public void run() {
		for (; ConfigZhilian.ZHILIAN_SEARCHLIST_P < ConfigZhilian.ZHILIAN_CITY_ENCODE.length; ConfigZhilian.ZHILIAN_SEARCHLIST_P++) {
				ConfigZhilian.ZHILIAN_SEARCHLIST_C = 3;//只是取计算机类的职位
//			for (; ConfigZhilian.ZHILIAN_SEARCHLIST_C < ConfigZhilian.ZHILIAN_CATEGORY_ENCODE.length; ConfigZhilian.ZHILIAN_SEARCHLIST_C++) {
				pageSum = 1; 
				for(int page = 1; page <= pageSum && page <= ConfigZhilian.ZHILIAN_SEARCHLIST_MAX_PAGE; page++) {
					ConfigZhilian.ZHILIAN_SEARCHLIST_TIMER = 0;
					patternAndWriteDB(ConfigZhilian.ZHILIAN_SEARCHLIST_P, ConfigZhilian.ZHILIAN_SEARCHLIST_C, page);
				}
//			}
//			ConfigZhilian.ZHILIAN_SEARCHLIST_C = 0;
		}
		ConfigZhilian.ZHILIAN_SEARCHLIST_P = 0;
		ConfigZhilian.ZHILIAN_SEARCHLIST_RUNNING = false;
	}
	
	public void close() {
		mysql.close();
	}
	
	private MysqlConn mysql = null;
	
	private static int pageSum = 1;
	
	private String getSearchPageHTML(int provIndex, int categroyIndex, int page) {
		//bTit"  </ta
		boolean startPattern = false;
		char[] startChar;
		if(page != 1) {
			startChar = new char[]{'b', 'T', 'i', 't'};
		} else {
			startChar = new char[]{'u', 'm', '"', '>'};
		}
		boolean startBool[] = { false, false, false, false };
		char endChar[] = { '<', 's', 'c', 'r' };
		boolean endBool[] = { false, false, false, false };
		int ch;
		InputStreamReader in = null;
		StringBuffer input = new StringBuffer();
		try {
			String url = "http://search.zhaopin.com/jobs/request.asp?page=" + page 
					+ "&PublishDate=1&JobLocation="
					+ ConfigZhilian.ZHILIAN_CITY_ENCODE[provIndex]
					+ "&SchJobType="
					+ ConfigZhilian.ZHILIAN_CATEGORY_ENCODE[categroyIndex];
			URL u = new URL(url);
			in = new InputStreamReader(u.openStream(), "UTF-8");
		} catch (Exception e) {
			if (Config.DEBUG_INFO) {
				e.printStackTrace();
			}
			return null;
		}
		/**
		 * 为了减少后面的正则匹配的字符串的长度 此处仅仅匹配ChinaHR搜索列表界面的部分代码 即以“bTit"”开头，以“<scr”结尾的部分
		 */
		try {
			while ((ch = in.read()) != -1) {
				if (!startPattern) {
					if (startBool[0]) {
						int i;
						for (i = 1; i < startBool.length && startBool[i]; i++)
							;
						if ((char) ch == startChar[i]) {
							if (i == startBool.length - 1) {
								startPattern = true;
								continue;
							}
							startBool[i] = true;
						} else {
							for (i = 0; i < startBool.length; i++) {
								startBool[i] = false;
							}
						}
					} else {
						if ((char) ch == startChar[0]) {
							startBool[0] = true;
						}
					}
					continue;
				} else {
					if (endBool[0]) {
						int i;
						for (i = 1; i < endBool.length && endBool[i]; i++)
							;
						if ((char) ch == endChar[i]) {
							if (i == endBool.length - 1) {
								break;
							}
							endBool[i] = true;
						} else {
							for (i = 0; i < endBool.length; i++) {
								endBool[i] = false;
							}
						}
					} else {
						if (endChar[0] == (char) ch) {
							endBool[0] = true;
						}
					}
					input.append((char) ch);
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}

		try {
			in.close();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return input.toString();
	}
	
	/**
	 * @return 实际写入数据库的JobId条数
	 * */
	private void patternAndWriteDB (int provIndex, int categoryIndex, int page) {
		String htmlContent = getSearchPageHTML(provIndex, categoryIndex, page);
		if(htmlContent == null) {
			return;
		}
		if(page == 1) {
			Pattern patternPageSum = Pattern.compile(
					"<b\\sclass=\"blue12 num\">[0-9]{1,3}/[0-9]{1,3}</b>",
					Pattern.CASE_INSENSITIVE);
			Matcher matchPageSum = patternPageSum.matcher(htmlContent);
			if(matchPageSum.find()) {
				String patternStr = htmlContent.substring(matchPageSum.start() + 22, matchPageSum.end() - 4);
				pageSum = Integer.parseInt(patternStr.substring(patternStr.indexOf((int)'/') + 1));
				System.out.println("Page Sum:\t" + pageSum);
			}
//			System.out.println(htmlContent);
		}
		Pattern patternURL = Pattern.compile(
				"http://jobs.zhaopin.com/P([A-Z]|[0-9]|/){46,50}.htm",
				Pattern.CASE_INSENSITIVE);
		Matcher matcherURL = patternURL.matcher(htmlContent);
		List<String> matchJobID = new ArrayList<String>();
		for (; matcherURL.find();) {
			String id = htmlContent.substring(matcherURL.start() + 25,
					matcherURL.end() - 4);
			matchJobID.add(id.substring(id.length() - 21)
					+ id.substring(0, id.indexOf((int) '/')));
		}
		int cntWriteDBOK = 0;
		for(int k = 0; k<matchJobID.size(); k++) {
			if( writeJobIdToDB(matchJobID.get(k), ConfigZhilian.ZHILIAN_CATEGORY_CODE[ConfigZhilian.ZHILIAN_SEARCHLIST_C])) {
				cntWriteDBOK++;
			}
		}
		String writeToLogStr = provIndex + "\t" + categoryIndex + "\t" + page
				+ "\t" + cntWriteDBOK + "\t" + matchJobID.size();
		File.writeLog(ConfigZhilian.ZHILIAN_SEARCHILIST_LOG_PATH, writeToLogStr);
	}
	
	private boolean writeJobIdToDB(String jobId, String category) {
		return mysql.executeInsert("INSERT INTO `zhilianjobid` (`jobId`, `category`) VALUES('" + jobId + "', '" + category +"');");
	}
}